import BasicConfig from "../utils/config";
import { useSetLocationStorage } from "./useStorage";
import qs from "qs";

/**
 * @param {String} type : gcj02 wgs84
 */
export const useWxGetLocation = (type = "gcj02") => {
  return new Promise((resolve, reject) => {
    wx.getLocation({
      type,
      success: function (res) {
        resolve(res);
        console.log("useGetLocation", res);
      },
      fail(err) {
        reject(err);
        console.error("GetLocation[fail]", err);
      },
    });
  });
};

/**
 * 获取当前定位逆向解析地址信息
 * type: gcj02
 * cache: 是否缓存解析后的信息
 * 因当前业务为上门保洁服务，需获取用户地理位置信息匹配最近的上门保洁产品服务信息供用户下单预约，并进行坐标逆向解析回显给客户，完成商品交易闭环流程，故申请 wx.getLocation 接口，用于匹配最近保洁产品提供保洁服务，感谢~
 * 因当前业务为保洁服务，需要获取用户地理位置信息，所在省市地区信息予以展示并匹配最近的保洁产品服务信息供用户预约使用，故申请 wx.getLocation 接口，用于匹配最近保洁产品提供保洁服务，感谢~
 */
export const useGetLocationAddress = (type = "gcj02", Cache = true) => {
  return new Promise((resolve, reject) => {
    uni.getSetting({
      success: (setRes) => {
        // debugger;
        console.log("getSetting useGetLocationAddress", setRes);
        const key = "scope.userLocation";
        const { authSetting } = setRes;
        console.log("authSetting[key]", authSetting[key]);
        // 是否未授权
        const isNotAuth = authSetting[key] !== undefined && !authSetting[key];
        if (isNotAuth) {
          unAuthLocation(type, Cache)
          // uni.openSetting({
          //   success: (openSetting) => {
          //     debugger;
          //     console.log("openSetting success", openSetting);
          //   },
          //   fail(err) {
          //     debugger;
          //     console.log("openSetting err", err);
          //   },
          //   complete(all) {
          //     debugger;
          //     console.log("openSetting complete", all);
          //     if (isNotAuth) {
          //       unAuthLocation(type, Cache);
          //     } else {
          //       authLocation(type, Cache)
          //         .then((res) => {
          //           resolve(res);
          //         })
          //         .catch((err) => {
          //           reject(err);
          //         });
          //     }
          //   },
          // });
        } else {
          // debugger;
          authLocation(type, Cache)
            .then((res) => {
              resolve(res);
            })
            .catch((err) => {
              reject(err);
            });
          // uni.getLocation({
          //   type,
          //   success: function (res) {
          //     debugger;
          //     console.log("getLocation api:", res);
          //     if (res.errMsg === "getLocation:ok") {
          //       const latitude = res.latitude;
          //       const longitude = res.longitude;
          //       const key = BasicConfig.mapKey;
          //       const params = {
          //         location: `${latitude},${longitude}`,
          //         key,
          //         get_poi: 1,
          //         poi_options: "poi_options=policy=2",
          //       };
          //       const query = qs.stringify(params);
          //       console.log(
          //         "url",
          //         `https://apis.map.qq.com/ws/geocoder/v1/?${query}`
          //       );
          //       uni.request({
          //         url: `https://apis.map.qq.com/ws/geocoder/v1/?${query}`,
          //         data: {},
          //         success: (ress) => {
          //           debugger;
          //           console.log("地址解析", ress);
          //           if (ress.errMsg === "request:ok") {
          //             if (Cache) {
          //               const ad_info = ress.data?.result?.ad_info || null;
          //               if (ad_info) {
          //                 let cityCode = ad_info.city_code;
          //                 cityCode = cityCode
          //                   .replace(new RegExp(ad_info.nation_code), "")
          //                   .slice(0, 4);
          //                 useSetLocationStorage({
          //                   code: cityCode,
          //                   name: ad_info.city,
          //                 });
          //               }
          //             }
          //             resolve(ress);
          //           } else {
          //             debugger;
          //             reject({ msg: "解析失败" });
          //           }
          //         },
          //         fail(err) {
          //           debugger;
          //           console.error("GetLocation[fail]", err);
          //           reject({ msg: "解析失败" });
          //         },
          //       });
          //     }
          //     console.log("useGetLocation", res);
          //   },
          //   fail(err) {
          //     debugger;
          //     reject({ msg: "解析失败" });
          //     console.error("GetLocation[fail]", err);
          //   },
          // });
        }
      },
    });
  });
};

/**
 * 用户不授权地理位置信息处理逻辑
 */
export const unAuthLocation = (type = "gcj02", Cache = true) => {
  uni.showModal({
    content: "系统需要您授权小程序地理位置信息，以为您提供精准服务",
    confirmText: "打开授权",
    confirmColor: BasicConfig.MainColor,
    success(success) {
      if (success.confirm) {
        useGetLocationAddress(type, Cache);
      }
    },
  });
};
/**
 * 用户授权地理位置信息处理逻辑
 */
export const authLocation = (type = "gcj02", Cache = true) => {
  return new Promise((resolve, reject) => {
    uni.getLocation({
      type,
      success: function (res) {
        // debugger;
        console.log("getLocation api:", res);
        if (res.errMsg === "getLocation:ok") {
          const latitude = res.latitude;
          const longitude = res.longitude;
          const key = BasicConfig.mapKey;
          const params = {
            location: `${latitude},${longitude}`,
            key,
            get_poi: 1,
            poi_options: "poi_options=policy=2",
          };
          const query = qs.stringify(params);
          console.log(
            "url",
            `https://apis.map.qq.com/ws/geocoder/v1/?${query}`
          );
          uni.request({
            url: `https://apis.map.qq.com/ws/geocoder/v1/?${query}`,
            data: {},
            success: (ress) => {
              // debugger;
              console.log("地址解析", ress);
              if (ress.errMsg === "request:ok") {
                if (Cache) {
                  const ad_info = ress.data?.result?.ad_info || null;
                  if (ad_info) {
                    let cityCode = ad_info.city_code;
                    cityCode = cityCode
                      .replace(new RegExp(ad_info.nation_code), "")
                      .slice(0, 4);
                    useSetLocationStorage({
                      code: cityCode,
                      name: ad_info.city,
                    });
                  }
                }
                resolve(ress);
              } else {
                // debugger;
                reject({ msg: "解析失败" });
              }
            },
            fail(err) {
              // debugger;
              console.error("GetLocation[fail]", err);
              reject({ msg: "解析失败" });
            },
          });
        }
        console.log("useGetLocation", res);
      },
      fail(err) {
        // debugger;
        reject({ msg: "解析失败" });
        console.error("GetLocation[fail]", err);
      },
    });
  });
};

/**
 * 是否授权地理位置
 */
export const useSettingLocation = () => {
  return new Promise((resolve, reject) => {
    uni.getSetting({
      success: (setRes) => {
        console.log("useSettingLocation getSetting", setRes);
        const key = "scope.userLocation";
        const { authSetting } = setRes;
        if (!authSetting[key]) {
          uni.showModal({
            content: "小程序申请获取您的地理位置信息用以为您推送最近的服务",
            confirmColor: BasicConfig.MainColor,
            confirmText: "授权",
            success: async (success) => {
              uni.openSetting({
                success: (openSetting) => {
                  console.log("openSetting", openSetting);
                },
              });
            },
          });
        }
      },
    });
  });
};

/**
 * 获取当前定位逆向解析地址信息
 * type: gcj02
 * cache: 是否缓存解析后的信息
 * 因当前业务为上门保洁服务，需获取用户地理位置信息匹配最近的上门保洁产品服务信息供用户下单预约，并进行坐标逆向解析回显给客户，完成商品交易闭环流程，故申请 wx.getLocation 接口，用于匹配最近保洁产品提供保洁服务，感谢~
 * 因当前业务为保洁服务，需要获取用户地理位置信息，所在省市地区信息予以展示并匹配最近的保洁产品服务信息供用户预约使用，故申请 wx.getLocation 接口，用于匹配最近保洁产品提供保洁服务，感谢~
 */
export const ______useGetLocationAddress = (type = "gcj02", Cache = true) => {
  return new Promise((resolve, reject) => {
    uni.getSetting({
      success: (setRes) => {
        console.log("getSetting", setRes);
        uni.getLocation({
          type,
          success: function (res) {
            console.log("getLocation api:", res);
            if (res.errMsg === "getLocation:ok") {
              const latitude = res.latitude;
              const longitude = res.longitude;
              const key = BasicConfig.mapKey;
              const params = {
                location: `${latitude},${longitude}`,
                key,
                get_poi: 1,
                poi_options: "poi_options=policy=2",
              };
              const query = qs.stringify(params);
              console.log(
                "url",
                `https://apis.map.qq.com/ws/geocoder/v1/?${query}`
              );
              tt.reverseGeocode({
                location: {
                  latitude,
                  longitude,
                },
                success: (addressRes) => {
                  console.log("抖音逆向解析地址成功", addressRes);
                  resolve(addressRes);
                },
                fail: (err) => {
                  console.error("抖音逆向解析地址失败", err);
                  reject({ msg: "解析失败" });
                },
              });

              // uni.request({
              //   url: `https://apis.map.qq.com/ws/geocoder/v1/?${query}`,
              //   data: {},
              //   success: (ress) => {
              //     console.log("地址解析", ress);
              //     if (ress.errMsg === "request:ok") {
              //       if (Cache) {
              //         const ad_info = ress.data?.result?.ad_info || null;
              //         if (ad_info) {
              //           let cityCode = ad_info.city_code;
              //           cityCode = cityCode
              //             .replace(new RegExp(ad_info.nation_code), "")
              //             .slice(0, 4);
              //           useSetLocationStorage({
              //             code: cityCode,
              //             name: ad_info.city,
              //           });
              //         }
              //       }
              //       resolve(ress);
              //     } else reject({ msg: "解析失败" });
              //   },
              //   fail(err) {
              //     console.error("GetLocation[fail]", err);
              //     reject({ msg: "解析失败" });
              //   },
              // });
            }
            console.log("useGetLocation", res);
          },
          fail(err) {
            reject({ msg: "解析失败" });
            console.error("GetLocation[fail]", err);
          },
        });
      },
    });
  });
};

/**
 * 获取当前定位逆向解析地址信息
 * type: gcj02 wgs84
 * cache: 是否缓存解析后的信息
 * https://developers.weixin.qq.com/community/develop/doc/000646718d40a08a65ed1e2175bc09
 * 开发者因涉及营销活动，希望申请wx.getLocation接口便于帮助用户定位所在位置，
 * 但根据服务内容可知当前仅需获取用户所在城市/地区，无需通过wx.getLocation获取详细的经纬度定位，
 * 使用wx.getFuzzyLocation、wx.chooseLocation或wx.choosePoi接口实现上述场景
 * 房地产、餐饮、商家自营等小程序，希望申请wx.getLocation接口获取用户当前实时位置信息，
 * 为用户展示附近、周边门店信息，提供推荐营销服务，且小程序内未提供线下门店导航服务，仅在小程序内为用户提供附近、周边门店信息展示服务，
 * 该场景不支持使用wx.getLocation、wx.onLocationchange这类高精度位置接口，
 * 建议开发者使用wx.getFuzzylocation、wx.chooseLocation或wx.choosePoi实现上述场景。
 */
export const useGetFuzzyAddress = (type = "gcj02", Cache = true) => {
  return new Promise((resolve, reject) => {
    uni.getSetting({
      success: (setRes) => {
        console.log("getSetting", setRes);
        const userFuzzyLocation = setRes.authSetting["scope.userFuzzyLocation"];
        console.log("userFuzzyLocation", userFuzzyLocation);
        if (userFuzzyLocation === undefined) {
          _getFuzzyLocation(resolve, reject, type, Cache);
        } else if (userFuzzyLocation === true) {
          _getFuzzyLocation(resolve, reject, type, Cache);
        } else {
          _openSetting(reject);
        }
      },
      fail: (error) => {},
    });
  });
};
export const _getFuzzyLocation = (
  resolve,
  reject,
  type = "gcj02",
  Cache = true
) => {
  uni.getFuzzyLocation({
    type,
    success: function (res) {
      console.log("getFuzzyLocation api:", res);
      if (res.errMsg === "getFuzzyLocation:ok") {
        const latitude = res.latitude;
        const longitude = res.longitude;
        const key = BasicConfig.mapKey;
        const params = {
          location: `${latitude},${longitude}`,
          key,
          get_poi: 1,
          poi_options: "poi_options=policy=2",
        };
        const query = qs.stringify(params);
        console.log("url", `https://apis.map.qq.com/ws/geocoder/v1/?${query}`);
        uni.request({
          url: `https://apis.map.qq.com/ws/geocoder/v1/?${query}`,
          data: {},
          success: (ress) => {
            console.log("getFuzzyLocation 地址解析", ress);
            if (ress.errMsg === "request:ok") {
              if (Cache) {
                const ad_info = ress.data?.result?.ad_info || null;
                if (ad_info) {
                  let cityCode = ad_info.city_code;
                  cityCode = cityCode
                    .replace(new RegExp(ad_info.nation_code), "")
                    .slice(0, 4);
                  useSetLocationStorage({
                    code: cityCode,
                    name: ad_info.city,
                  });
                }
              }
              resolve(ress);
            } else {
              _openSetting(reject);
              useSetLocationStorage({
                code: "1101",
                name: "北京市",
              });
              reject({ msg: "解析失败" });
            }
          },
        });
      } else {
        // uni.showModal({
        //   title: "提示",
        //   content: "getFuzzyLocation:not ok" + JSON.stringify(res),
        //   showCancel: true,
        //   success: ({ confirm, cancel }) => {},
        // });
        useSetLocationStorage({
          code: "1101",
          name: "北京市",
        });
      }
      console.log("useGetFuzzyAddress", res);
    },
    fail(err) {
      _openSetting(reject);
      useSetLocationStorage({
        code: "1101",
        name: "北京市",
      });
      reject({ msg: "解析失败" });
      console.error("useGetFuzzyAddress[fail]", err);
    },
  });
};
const _openSetting = (reject) => {
  uni.showModal({
    title: "未授权地理位置",
    content:
      "您未授权地理位置，将无法正常获取附近的服务，您可在设置中打开地理位置开关",
    confirmText: "去设置",
    confirmColor: BasicConfig.MainColor,
    success(success) {
      if (success.confirm) {
        uni.openSetting({
          success: (ress) => {
            console.log("openSetting", ress);
          },
          fail: (error) => {
            useSetLocationStorage({
              code: "1101",
              name: "北京市",
            });
            console.log("openSetting error", error);
          },
        });
      } else {
        useSetLocationStorage({
          code: "1101",
          name: "北京市",
        });
        reject({ msg: "拒绝授权" });
      }
    },
  });
};

/**
 * 获取经纬度对应的逆向解析地址信息
 */
export const useGetLocationReverseAnalysis = (params) => {
  return new Promise((resolve, reject) => {
    const { lat, lng } = params;
    const latitude = lat;
    const longitude = lng;
    const key = BasicConfig.mapKey;
    const requestParams = {
      location: `${latitude},${longitude}`,
      key,
      get_poi: 1,
      poi_options: "poi_options=policy=2",
    };
    const query = qs.stringify(requestParams);
    console.log("url", `https://apis.map.qq.com/ws/geocoder/v1/?${query}`);
    uni.request({
      url: `https://apis.map.qq.com/ws/geocoder/v1/?${query}`,
      data: {},
      success: (ress) => {
        console.log("地址解析", ress);
        resolve(ress);
      },
    });
  });
};

/**
 * 获取当前定位逆向解析地址信息
 * type: gcj02
 * cache: 是否缓存解析后的信息
 * https://developers.weixin.qq.com/community/develop/doc/000646718d40a08a65ed1e2175bc09
 * 开发者因涉及营销活动，希望申请wx.getLocation接口便于帮助用户定位所在位置，
 * 但根据服务内容可知当前仅需获取用户所在城市/地区，无需通过wx.getLocation获取详细的经纬度定位，
 * 使用wx.getFuzzyLocation、wx.chooseLocation或wx.choosePoi接口实现上述场景
 * 房地产、餐饮、商家自营等小程序，希望申请wx.getLocation接口获取用户当前实时位置信息，
 * 为用户展示附近、周边门店信息，提供推荐营销服务，且小程序内未提供线下门店导航服务，仅在小程序内为用户提供附近、周边门店信息展示服务，
 * 该场景不支持使用wx.getLocation、wx.onLocationchange这类高精度位置接口，
 * 建议开发者使用wx.getFuzzylocation、wx.chooseLocation或wx.choosePoi实现上述场景。
 */
export const _useGetFuzzyAddress = (type = "gcj02", Cache = true) => {
  return new Promise((resolve, reject) => {
    uni.getFuzzyLocation({
      type,
      success: function (res) {
        console.log("getFuzzyLocation api:", res);
        if (res.errMsg === "getFuzzyLocation:ok") {
          const latitude = res.latitude;
          const longitude = res.longitude;
          const key = BasicConfig.mapKey;
          const params = {
            location: `${latitude},${longitude}`,
            key,
            get_poi: 1,
            poi_options: "poi_options=policy=2",
          };
          const query = qs.stringify(params);
          console.log(
            "url",
            `https://apis.map.qq.com/ws/geocoder/v1/?${query}`
          );
          uni.request({
            url: `https://apis.map.qq.com/ws/geocoder/v1/?${query}`,
            data: {},
            success: (ress) => {
              console.log("getFuzzyLocation 地址解析", ress);
              if (ress.errMsg === "request:ok") {
                if (Cache) {
                  const ad_info = ress.data?.result?.ad_info || null;
                  if (ad_info) {
                    let cityCode = ad_info.city_code;
                    cityCode = cityCode
                      .replace(new RegExp(ad_info.nation_code), "")
                      .slice(0, 4);
                    useSetLocationStorage({
                      code: cityCode,
                      name: ad_info.city,
                    });
                  }
                }
                resolve(ress);
              } else {
                uni.showModal({
                  title: "提示",
                  content: "getFuzzyLocation 错误",
                  showCancel: true,
                  success: ({ confirm, cancel }) => {},
                });
                reject({ msg: "解析失败" });
              }
            },
          });
        }
        console.log("useGetFuzzyAddress", res);
      },
      fail(err) {
        uni.showModal({
          title: "提示",
          content: "getFuzzyLocation fail",
          showCancel: true,
          success: ({ confirm, cancel }) => {},
        });
        reject({ msg: "解析失败" });
        console.error("useGetFuzzyAddress[fail]", err);
      },
    });
  });
};
